<?php
namespace Admin\Controller;

class GroupController extends AdminController {
    //用户组
    public function index(){
        $group = M('Group')->select();
        $this->assign('group',$group);
        $this->display();
    }

    //添加用户组
    public function add(){
        if(IS_POST){
            $group = M('Group')->where(array('group_name'=>I('post.group_name')))->select();
            if($group){
                $this->error('该分组名已经存在，不可使用');
            }
            $rules = I('post.rules');
            if(isset($rules)){
                $rules = (array)I('post.rules');
                sort($rules);
                $str = '';
                foreach($rules as $k => $v){
                    $str.=$v.',';
                }
                $rules = rtrim($str,',');
                $data['rules'] = $rules;
            }
            $data['group_name'] = I('post.group_name');
            $data['status'] = intval(I('post.status'));
            if(M('Group')->add($data)){
                $this->success('添加成功',U('index'));
            }else{
                $this->error('添加失败');
            }

        }else{
            //dump($user);exit();
            $this->display();
        }
    }

    //删除用户组
    public function del(){
        //判断分组下面是否有用户，有的话不能删除
        $member = M('Member')->where(array('group_id'=>intval(I('get.id'))))->select();
        if($member){$this->error('该分组下面有代理用户，不能直接删除！');}
        if(M('Group')->delete(intval(I('get.id')))){
            $this->success('删除成功');
        } else {
            $this->error('删除失败！');
        }
    }

    //编辑用户组
    public function edit(){
        if(IS_POST){


            $rules = I('post.rules');
            if(isset($rules)){
                $rules = (array)I('post.rules');
                sort($rules);
                $str = '';
                foreach($rules as $k => $v){
                    $str.=$v.',';
                }
                $rules = rtrim($str,',');
                $data['rules'] = $rules;
            }
            $data['group_name'] = I('post.group_name');
            $data['status'] = intval(I('post.status'));
            $data['id'] = intval(I('post.id'));
            //dump($data);exit();
            if(M('Group')->save($data)){
                $this->success('修改成功',U('index'));
            }else{
                $this->error('修改失败');
            }
        }else{
            $group = M('Group') -> find(I('get.id'));
            $str = $group['rules'];
            $rules = array();
            $rules = explode(',', $str);
            $rules = json_encode($rules);
            $this->assign('rules',$rules);
            $this->assign('group',$group);
            $this->display();
        }
    }
}